var viewPortWidth = getViewPortWidth(), //屏幕宽
    viewPortHeight = getViewPortHeight();   //屏幕高

window.onload=function () {
    init();
};

var canvas = document.getElementById("canvas");
canvas.width=viewPortWidth;
canvas.height=viewPortHeight;
var stage =new createjs.Stage(canvas);

//实时监听stage画布更新
createjs.Ticker.addEventListener("tick", handleTicker);
function handleTicker(){
    stage.update();
}

//初始化函数
function init() {
    drawBall();
}

//开始画球
function drawBall() {
    var arr = [];
    var itv = setInterval(function () {
        var ballProporty = ballProportys();
        var ball = new Ball(ballProporty);
        var ballStone = ball.getBall();
        arr.push(ballStone);
        stage.addChild(ballStone);
        createjs.Ticker.setFPS(60);
        createjs.Ticker.on('tick',tick);
        function tick() {
            var x = ballStone.x + ball.xspeed;
            var y = ballStone.y + ball.yspeed;
            if(x>viewPortWidth ||x<0){
                ball.xspeed = (-1)*ball.xspeed;
            }
            if(y>viewPortHeight ||y<0){
                ball.yspeed = (-1)*ball.yspeed;
            }
            ballStone.x =x;
            ballStone.y =y;
        }
        if (arr.length>=10){
            window.clearInterval(itv);
        }
    },1000);
}

stage.addEventListener("click",handleClick);
function handleClick() {
    // Click happened;
    console.log("The mouse is clicked.");
}
stage.addEventListener("mousedown",handlePress);
function handlePress() {
    // A mouse press happened.
    // Listen for mouse move while the mouse is down:
    console.log("The mouse is pressed.");
    stage.addEventListener("mousemove",handleMove);
}
function handleMove() {
    // Check out the DragAndDrop example in GitHub for more
    console.log("The mouse is moved.");
}


function ballProportys() {
    var ballProportys = {
        color:"rgb(" + parseInt(Math.random() * 256) + "," + parseInt(Math.random() * 256) + "," + parseInt(Math.random() * 256) + ")",
        top:0,
        left:0,
        radius:Math.random()*10+20,
        x:20,
        y:20,
        xspeed:Math.random()*3+3,
        yspeed:Math.random()*3+3
    };
    return ballProportys;
}

function Ball(data) {
    this.color=data.color;      //颜色
    this.x=data.x;             //圆心x轴的位置
    this.y=data.y;             //圆心y轴的位置
    this.radius=data.radius;    //半径
    this.top=data.top;          //距离上部的距离
    this.left=data.left;        //距离左侧的位置
    this.xspeed = data.xspeed;     //x轴方向的速度
    this.yspeed =data.yspeed;       //y轴方向的速度

    this.getBall=function () {
        var circle = new createjs.Shape();
        circle.graphics.beginFill(this.color).drawCircle(this.top, this.left, this.radius);
        circle.x = this.x;
        circle.y = this.y;
        return circle;
    };
}

